<?php

namespace App\Services;

use App\Repository\Contracts\MenuRepository;
use App\Traits\Arr as TreeArr;
use Illuminate\Support\Facades\Cache;

class MenuService
{
    use TreeArr;
    /**
     * @var MenuRepositoryEloquent
     */
    protected $menuRepository;

    public function __construct(MenuRepository $menuRepository)
    {

        $this->menuRepository = $menuRepository;
    }

    private function cacheAllData()
    {
        return Cache::remember('menus', 10, function () {
            return $this->menuRepository->toEntity()->get();
        })->toArray();
    }

   /**
    * Get Menus  and paginate.
    *
    * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator
    */
    public function getMenus()
    {
        return $this->menuRepository->get();
    }

    /**
     * 添加界面展示无限极分类
     */

    public function getTree()
    {
        return $this->tree($this->cacheAllData(), 'name', 'id', 'parent_id');
    }

    
    /**
     * 添加左侧展示无限极分类
     */

    public function getMenuTree()
    {
        return $this->channelLevel($this->cacheAllData(), 0, "&nbsp;", 'id', 'parent_id');
    }



    /**
     * 无限极分类列表
     */
    public function getTreeList()
    {
        $categories = collect($this->cacheAllData())->groupBy('parent_id');
        if($categories->isNotEmpty()){
            $categories['root'] = $categories[0];
            unset($categories[0]);
        }
        return $categories->toArray();
        // return $this->channelLevel($this->cacheAllData(), 0, "&nbsp;", 'id', 'parent_id');
    }
   /**
    * Get one Menu  by primary key.
    *
    * @param $id
    * @return \Illuminate\Database\Eloquent\Model|\Illuminate\Database\Eloquent\Collection|static[]|static|null
    */
    public function getMenu($id)
    {
        return $this->menuRepository->find($id);
    }

   /**
    * Create a new line on Menu.
    *
    * @param array $data
    * @return \Illuminate\Database\Eloquent\Model|$this
    */
    public function storeMenu($data)
    {
        cache()->forget('menus');
        return $this->menuRepository->create($data);
    }

   /**
    * Update Menu one line by primary key.
    *
    * @param $id
    * @param array $data
    * @return int
    */
    public function updateMenu($id, $data)
    {
        return $this->menuRepository->update($id, $data);
    }

   /**
    * Delete Menu one line by primary key.
    *
    * @param $id
    * @return mixed
    */
    public function deleteMenu($id)
    {
        return $this->menuRepository->deleteById($id);
    }

}